package com.yswy.app.service.impl;

import com.alibaba.nacos.common.util.Md5Utils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yswy.app.dto.TgCallBackIdReids;
import com.yswy.app.service.AppUserService;
import com.yswy.app.service.SysConfigService;
import com.yswy.app.service.TgCallBackHdIdService;
import com.yswy.app.service.TgChannleService;
import com.yswy.common.runnableUtil.Pooled;
import com.yswy.common.utils.StringUtils;
import com.yswy.common.utils.http.HttpUtils;
import com.yswy.common.utils.redis.RedisConstants;
import com.yswy.common.utils.redis.RedisUtil;
import com.yswy.domain.entity.TgCallBackConf;
import com.yswy.domain.entity.TgCallBackHdId;
import com.yswy.domain.entity.UserDeviceInfo;
import com.yswy.domain.mapper.TgBindCsjAdMapper;
import com.yswy.domain.mapper.TgCallBackHdIdMapper;
import com.yswy.domain.mapper.TgChannleChildMapper;
import com.yswy.domain.vo.dto.TgDeviceHd;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Slf4j
@Service
public class TgCallBackHdIdServiceImpl extends ServiceImpl<TgCallBackHdIdMapper, TgCallBackHdId>
        implements TgCallBackHdIdService {
    @Autowired
    private RedisUtil redisUtil ;
    @Autowired
    private TgChannleService tgChannleService ;
    @Autowired
    private SysConfigService sysConfigService ;
    @Autowired
    private AppUserService appUserService ;
    @Autowired
    private TgChannleChildMapper tgChannleChildMapper ;
    @Autowired
    private TgBindCsjAdMapper tgBindCsjAdMapper ;

    @Override
    @Pooled(executor = "tgCallBackIdInp", poolOverAct = Pooled.PoolOverAct.NEW_THREAD)
    public void addTgCallBackHdId(String channle , TgDeviceHd tgDeviceHd, Integer activeType) {
        if (StringUtils.isEmpty(tgDeviceHd.getA_oId()))return;
        if (StringUtils.isEmpty(channle))return;
        TgCallBackConf tgCallBackConf = tgChannleService.getTgCallBackConf(channle);
        if (tgCallBackConf == null){
            log.info("互动渠道"+channle+"未配置参数");
            return;
        }
        //回传类型  0 付费  1 广告ecpm
        Integer isCallbackType =tgCallBackConf.getCallbackType();
        //登录缓存时间（用于登录回传失效时间）
        Integer isCallbackLoginCacheTime =tgCallBackConf.getLoginCacheTime();

        TgCallBackHdId tgCallBackHdId = new TgCallBackHdId(channle , tgDeviceHd, activeType  ,isCallbackType );

        String oaidMd5 = tgCallBackHdId.getOaidMd5();
        String IpMd5 = Md5Utils.getMD5(tgCallBackHdId.getChannelIp() , "utf8");
        String oaidMd5RES = RedisConstants.tgBackLoginLog_Hd+oaidMd5;
        String IpMd5Md5RES = RedisConstants.tgBackLoginLog_Hd+IpMd5;
        String callbackparamCrc = RedisConstants.tgBackLoginLog_Hd+tgCallBackHdId.getCallbackparamCrc();
        if (!redisUtil.hasKey(callbackparamCrc)){
            Integer count = count(new LambdaQueryWrapper<TgCallBackHdId>()
                    .eq(TgCallBackHdId::getCallbackparamCrc ,tgCallBackHdId.getCallbackparamCrc()));
            if (count<=0){
                save(tgCallBackHdId);
                redisUtil.setForObjectTimeCustom(callbackparamCrc, tgCallBackHdId, 5, TimeUnit.MINUTES);
                if (StringUtils.isNotEmpty(tgCallBackHdId.getOaidMd5())){
                    redisUtil.setForObjectTimeCustom(oaidMd5RES, tgCallBackHdId, isCallbackLoginCacheTime, TimeUnit.HOURS);
                }
                if (StringUtils.isNotEmpty(tgCallBackHdId.getChannelIp())){
                    redisUtil.setForObjectTimeCustom(IpMd5Md5RES, tgCallBackHdId, isCallbackLoginCacheTime, TimeUnit.HOURS);
                }
            }
        }
    }

    @Override
    public TgCallBackIdReids getTgCallBackHdId(Long userId, String ip, String key) {
        TgCallBackHdId tgCallBackId = null ;
//        String Modelip = userDeviceInfo.getModelInfo()+ip ;
        String modelIpMd5 = Md5Utils.getMD5(ip.replaceAll("\\s" , "") , "utf8");
        String modelIpMd5RES = key+modelIpMd5;
        TgCallBackIdReids tgCallBackIdReids = new TgCallBackIdReids();
         if (redisUtil.hasKey(modelIpMd5RES)){
            tgCallBackId = (TgCallBackHdId)redisUtil.getObejct(modelIpMd5RES);
            tgCallBackIdReids = new TgCallBackIdReids(tgCallBackId , modelIpMd5 );
        }
        redisUtil.delete(modelIpMd5RES);
        return tgCallBackIdReids;
    }

    @Override
    public String hdCallBackLogin(Long userId, String ip) {
        TgCallBackIdReids tgCallBackIdReids =  getTgCallBackHdId( userId,  ip,RedisConstants.tgBackLoginLog_Hd);
        TgCallBackHdId tgCallBackId  = tgCallBackIdReids.getTgCallBackHdId() ;
        String modelIpMd5 = tgCallBackIdReids.getModelIpMd5();
        if (tgCallBackId != null){
            TgCallBackConf tgCallBackConf = tgChannleService.getTgCallBackConf(tgCallBackId.getChannle());
            if (tgCallBackConf == null){
                log.info("互动渠道"+tgCallBackId.getChannle()+"未配置参数");
                return null;
            }
            //缓存时间（用于关键事件回传失效时间）
            Integer isCallbackEventCacheTime =tgCallBackConf.getEventCacheTime();
            //回传登录Key  active
            String loginKey =tgCallBackConf.getLoginKey();
            //是否回传关键事件
            Integer isCallBackEvent =tgCallBackConf.getIsCallBackEvent();

            tgCallBackId.setUserId(userId);
            //回传
            if (tgCallBackId.getIsCallbackType()==0){
//                Boolean isDeduction = tgChannleService.isDeduction(tgCallBackId.getChannle() , null);
                Boolean isDeduction = false ;
                if (isDeduction){
                    //不回传
                    tgCallBackId.setIsCallbackLogin(2);
                }else {
                    tgCallBackId.setIsCallbackLogin(1);
                    //回传
                    callBack(tgCallBackId ,loginKey );
                    if (isCallBackEvent == 1){
                        redisUtil.setForObjectTimeCustom(RedisConstants.tgBackPayLog_Hd+modelIpMd5, tgCallBackId, isCallbackEventCacheTime, TimeUnit.HOURS);
                    }
                }
            }else {
                tgCallBackId.setIsCallbackLogin(2);
                log.info("互动渠回传类型不执行：userID：" +userId);
            }
            updateById(tgCallBackId);
            return tgCallBackId.getChannle();
        }else {
            log.info("互动渠道用户登录未匹配上：userID：" +userId);
            return null ;
        }
    }

    @Override
    public String hdCallBackPay(Long userId, String ip , Integer price) {
        TgCallBackIdReids tgCallBackIdReids = getTgCallBackHdId( userId,  ip,RedisConstants.tgBackPayLog_Hd);
        TgCallBackHdId tgCallBackHdId = tgCallBackIdReids.getTgCallBackHdId() ;
        if (tgCallBackHdId != null){
            TgCallBackConf tgCallBackConf = tgChannleService.getTgCallBackConf(tgCallBackHdId.getChannle());
            if (tgCallBackConf == null){
                log.info("互动渠道"+tgCallBackHdId.getChannle()+"未配置参数");
                return null;
            }
            //回传关键事件Key game_addiction
            String eventKey =tgCallBackConf.getEventKey();
            tgCallBackHdId.setUserId(userId);
            Boolean isDeduction = tgChannleService.isDeduction(tgCallBackHdId.getChannle() , price);
            if (isDeduction){
                //不回传
                tgCallBackHdId.setIsCallbackPay(2);
            }else {
                //回传
                callBack(tgCallBackHdId ,eventKey);
                tgCallBackHdId.setIsCallbackPay(1);
            }

            updateById(tgCallBackHdId);
            return tgCallBackHdId.getChannle();
        }else {
            return null ;
        }
    }

    public void callBack(TgCallBackHdId tgCallBackId , String eventEype){
        String modeStr = sysConfigService.selectConfigByKey("sys.tuiya.key");
        Map<String, Object> map = new HashMap<>();
        map.put("advertKey", modeStr);
        map.put("a_oId", tgCallBackId.getCallbackparam());
        map.put("subType", eventEype);
        map.put("ua", tgCallBackId.getUaStr());
        map.put("device", tgCallBackId.getDeviceMd5());
        map.put("ip", tgCallBackId.getChannelIp());
        String s = null;
        try {
            s = HttpUtils.post("https://activity.tuia.cn/log/effect/v2", map);
            log.info("推呀回调输入手机:" + s);
        } catch (IOException e) {
            log.info("推呀失败:");
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<>();
        map.put("advertKey", "CFEF4AA9C4B90C718BF82EED95BF13BF");
        map.put("a_oId", "taw-12528930174650721");
        map.put("subType", 6);
        map.put("ua", "Mozilla%2F5.0%20%28Linux%3B%20Android%2011%3B%20CMA-AN00%20Build%2FHONORCMA-AN00%3B%20wv%29%20AppleWebKit%2F537.36%20%28KHTML%2C%20like%20Gecko%29%20Version%2F4.0%20Chrome%2F83.0.4103.106%20Mobile%20Safari%2F537.36KSADSDK_V3.3.53_com.chituo.hykc_1.0.2.2023.1102.1111");
        map.put("device", "defVil");
        map.put("ip", "223.104.122.37");
        String s = null;
        try {
            s = HttpUtils.post("https://activity.tuia.cn/log/effect/v2", map);
            log.info("推呀回调输入手机:" + s);
        } catch (IOException e) {
            log.info("推呀失败:");
            e.printStackTrace();
        }
    }
}

